# -*- coding: utf-8 -*-
"""
@time：  2021/06/03  20:36
@Auto：Mr. xingye  993843278
@Company 星野训练营 99384378@qq.com
@Function: APP关键字库

"""
import json
import os,threading,time
from appium import webdriver

class APP:
    """APP关键字库"""

    def __init__(self):
        self.port = '4723'
        self.driver: webdriver.Remote = None

    def runappium(self, appiumpath='', port=''):
        """多线程执行appium服务"""
        if appiumpath is None or appiumpath == '':
            appiumpath = r"C:\Users\Xy\AppData\Local\Programs\Appium"

        if port is None or port == '':
            port = '4723'

        self.port = port
        appiumpath += r"\resources\app\node_modules\appium\build\lib\main.js --port " + port

        def run_appium(appium_path):
            """
            定义一个函数，专门处理这个阻塞的业务
            :param appium_path: appium的路径
            :return:
            """
            # 当我们启动appium服务器的时候，阻塞了主线程
            os.system("node " + appium_path)

        th = threading.Thread(target=run_appium, args=(appiumpath,))
        th.start()
        # 等待appium启动完成
        time.sleep(5)
        print("进程启动成功————————————————————————————————")



    def run_app(self,conf:str=''):
        print(1111111111111111111111111,conf)
        conf = json.loads(conf)
        print(22222222222,type(conf))
        self.driver = webdriver.Remote("http://127.0.0.1:%s/wd/hub" % self.port,conf)
        # 等待app启动完成
        time.sleep(6)
        self.driver.implicitly_wait(10)

    def killappium(self):
        """结束appium服务"""
        os.system('taskkill /F /IM node.exe')

    def __find_ele(self, locator: str = ''):
        """
        元素定位，支持三种方式
        :param locator: accessibility_id，id，xpath
        :return:
        """
        if locator.__contains__(':id/'):
            """id定位"""
            ele = self.driver.find_element_by_id(locator)
        elif locator.startswith('/'):
            # xpath定位
            ele = self.driver.find_element_by_xpath(locator)
        else:
            ele = self.driver.find_element_by_accessibility_id(locator)

        return ele

    def Click(self, locator=''):
        """点击"""
        ele = self.__find_ele(locator)
        ele.click()

    def Input_Text(self, locator='', value=''):
        """输入文本"""
        ele = self.__find_ele(locator)
        ele.click()
        ele.clear()
        ele.send_keys(value)

    def Sleep(self, t='1'):
        """等待"""
        try:
            t = float(t)
        except:
            t = 1
        time.sleep(float(t))

    def quit(self):
        self.driver.quit()

    def Back(self, t='1'):
        """返回键"""
        try:
            t = float(t)
        except:
            t = 1
        self.driver.back()
        time.sleep(t)
